package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.ziDyException;
import com.atguigu.yygh.hosp.mapper.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public void save(Map<String, Object> paramMap) {

        String s = JSONObject.toJSONString(paramMap);

        Schedule schedule = JSONObject.parseObject(s, Schedule.class);

        //根据医院编号 和 排班编号查询
        Schedule scheduleExist = scheduleRepository.
                getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(),schedule.getHosScheduleId());

        if(scheduleExist!=null) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }

    }

    @Override
    public Page<Schedule> findPage(Map<String, Object> switchMap) {

        String hoscode = (String)switchMap.get("hoscode");
        int page = StringUtils.isEmpty(switchMap.get("page")) ? 1 : Integer.parseInt((String)switchMap.get("page"));
        int limit = StringUtils.isEmpty(switchMap.get("limit")) ? 10 : Integer.parseInt((String)switchMap.get("limit"));

        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");

        Pageable pageable = PageRequest.of(page-1, limit, sort);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        Example<Schedule> example = Example.of(schedule, matcher);

        Page<Schedule> all = scheduleRepository.findAll(example, pageable);

        return all;
    }

    @Override
    public void deleteById(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode,hosScheduleId);

        if (schedule != null){
            scheduleRepository.deleteById(schedule.getId());

        }

    }

    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {

        Map<String, Object> map = new HashMap<>();

        //使用mongoTemplate来实现聚合查询
        //创建查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                                    .and("depcode").is(depcode);

        //使用mongoTematle查询
        Aggregation aggregation = Aggregation.newAggregation(
                //匹配条件
                Aggregation.match(criteria),

                Aggregation.group("workDate").first("workDate").as("workDate")
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),

                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //获取到查询后得对象
        List<BookingScheduleRuleVo> mappedResults = aggregate.getMappedResults();

        //分组查询的总记录数
        Aggregation aggregation1 = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate1 = mongoTemplate.aggregate(aggregation1, Schedule.class, BookingScheduleRuleVo.class);
        //查询出总记录数
        int total = aggregate1.getMappedResults().size();

        //将mappedResults中得日期改为周几周几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : mappedResults) {

            String dayOfWeek = this.getDayOfWeek(new DateTime(bookingScheduleRuleVo.getWorkDate()));

            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //将结果封装返回
        map.put("bookingScheduleRuleList",mappedResults);
        map.put("total",total);
        return map;
    }

    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {

        Date date = new DateTime(workDate).toDate();
        List<Schedule> list = scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,date);

        list.stream().forEach(item->{
            this.packageSchedule(item);
        });

        return list;
    }

    //根据id获取排版详情
    @Override
    public Schedule getById(String id) {

        Schedule schedule = scheduleRepository.findById(id).get();
        Schedule schedule1 = this.packageSchedule(schedule);
        return schedule1;
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        //进行数据的封装
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();

        //根据id查出排版数据
        Schedule schedule = this.getById(scheduleId);
        if(schedule == null){
            throw new ziDyException(20001,"数据异常");
        }
        //将查询到的数据进行封装
        Schedule schedule1 = this.packageSchedule(schedule);

        //查询医院的预约规则信息
        Hospital hospital = hospitalService.show(schedule1.getHoscode());
        if (hospital == null){
            throw new ziDyException(20001,"数据异常");
        }
        //将医院信息中的预约规则取出来
        BookingRule bookingRule = hospital.getBookingRule();

        //获得封装后的数据，将数据封装到scheduleOrderVo中，返回
        //医院编号
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        //医院名称
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        //科室编号
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        //科室名称
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        //排版编号
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        //剩余预约数
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        //医生职称
        scheduleOrderVo.setTitle(schedule.getTitle());
        //安排日期
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        //安排时间
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        //医师服务费
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截至天数(（如：就诊前一天为-1，当天为0）)
        //获取到的这个是距离退号的剩余天数，就诊前一天为-1 当天为0
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }
    //修改可预约数和剩余预约数
    @Override
    public void update(Schedule schedule) {
        scheduleRepository.save(schedule);
    }

    //获取挂号详情
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {

        //首先根据hoscode去查询医院的预约规则
        Hospital hospital = hospitalService.show(hoscode);
        //获取到医院的信息以后，从医院的hospital中有一个bookingRule对象，里面存到是医院的预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        //使用医院的规则，带分页先获取到预约周期内的日期数据
        //这里的这个方法是我们自己定义在impl中的方法
        IPage iPage = this.getListDate(page, limit, bookingRule);
        //将分页中的数据取出
        List<Date> dateList = iPage.getRecords();

        //设置条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);

        //使用mongontample聚合查询，将数据查询到
        Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
                Aggregation.group("workDate")
                        .first("workDate").as("workDate")
                .count().as("docCount")
                .sum("availableNumber").as("availableNumber")
                .sum("reservedNumber").as("reservedNumber")
        );

        //s使用mongontemaple查询
        AggregationResults<BookingScheduleRuleVo> bookingScheduleRuleVos = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        //将数据中的dayOfWeek属性转换成周几
        List<BookingScheduleRuleVo> mappedResults = bookingScheduleRuleVos.getMappedResults();
        //将获取到的数据转换成一个map集合，方便后面的操作
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        //判断如果mappedResults不为空的话在进行操作
        if (mappedResults != null){
            scheduleVoMap = mappedResults.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,BookingScheduleRuleVo->BookingScheduleRuleVo));
        }

        //获取可预约排班规则
        //创建一个list来存放预约的信息等
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();

        for (int i=0, len=dateList.size(); i<len; i++) {

            //将map中的值取出来进行操作
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(dateList.get(i));
            //判断，如果bookingScheduleRuleVo对象为空的话，说明这天医院不能进行预约，没有号
            if (bookingScheduleRuleVo == null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            //将bookingScheduleRuleVo中的dayOfWeek转换为周几
            String dayOfWeek = bookingScheduleRuleVo.getDayOfWeek();

            String dayOfWeek1 = this.getDayOfWeek(new DateTime(dayOfWeek));

            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek1);

            //设置可预约日期
            bookingScheduleRuleVo.setWorkDate(dateList.get(i));
            bookingScheduleRuleVo.setWorkDateMd(dateList.get(i));


            //判断如果是最后一条的话，显示即将放号
            if (i == dateList.size()-1 && page == iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else{
                bookingScheduleRuleVo.setStatus(0);
            }
            //判断当前时间是否过了当天的挂号时间，如果过了就显示停止挂号
            if (i == 0 && page == 1){
//                String stopTime = bookingRule.getStopTime();
//                DateTime dateTime = new DateTime(stopTime);
                DateTime dateTime = this.getDateTime(new Date(), bookingRule.getStopTime());
//                System.out.println("dateTime = " + dateTime);
                if(dateTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            /**
             * 0是正常  -1是停止挂号  1是即将放号
             */
            //最终将数据加到list集合中
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        Map<String, Object> result = new HashMap<>();
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
//使用分页加条件，筛选出日期，返回
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {

        //获取放号时间
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());

        Integer cycle = bookingRule.getCycle();//这个取出的是预约周期

        //判断，如果当前时间超过当天的放号时间的话，就往后在延续一天，将预约周期加1
        if (releaseTime.isBeforeNow()){
            cycle += 1;
        }

        //准备一个list集合来存放我们返回的信息
        List<Date> dateList = new ArrayList<>();
        //循环预约周期，获取每天挂号的时间
        for (Integer i = 0; i < cycle; i++) {
            //将当前时间加上i天，每次循环+1
            DateTime dateTime = new DateTime().plusDays(i);
            //将日期格式变换成yyyy-MM-dd格式的数据
            String s = dateTime.toString("yyyy-MM-dd");
            //将生成好的日期加入到list集合中
            dateList.add(new DateTime(s).toDate());
        }

        //设置分页数据
        List<Date> pageDateList = new ArrayList<>();
        //起始页
        int start = (page-1)*limit;
        //每页记录数
        int end = (page-1)*limit+limit;
        //判断如果是最后一页显示的条数
        if(end > dateList.size()){
            end = dateList.size();
        }
        //循环，将数据取出。加入到pageDateList集合中
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        //设置分页数据
        //1.参数1：起始页 参数2：每页记录数 参数3：总条数
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page,7,dateList.size());
        //将数据set到ipage中
        iPage.setRecords(pageDateList);
        //生成分页，将分页数据返回
        return iPage;

    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private Schedule packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.show(schedule.getHoscode()).getHosname());
        //设置科室名称
        schedule.getParam().put("depname",
                departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));

        return schedule;

    }
}
